/* eslint-disable no-async-promise-executor */
const model = require("../models/model")
const Myorder = model.shopOrder.ShopOrder
const MyGoodsList = model.goodsdetailsList.MyGoodsList

const { Op } = require("sequelize") // 操作符
const { verify } = require('../models/tokenFn')

// 获取选择的list数据
function listSelect(list) {
  return new Promise(async(resolve) => {
    if (typeof(list) == 'string') {
      const listData = JSON.parse(list)
      if (listData.length > 0) {
        let fag = 0
        let dataList = []
        listData.forEach(item => {
          // 一个商品的list不可能同时出现 无规格和有规格两种list
          // 判断 可以直接else返回，不会发生 循环中异步返回了值导致错误
          if (item.listId) {
            MyGoodsList.findOne({ where: { id: item.listId }}).then(res => {

              fag ++
              res['cart_num'] = item.cart_num
              for(let key in res) {
                if (res[key] == null) {
                  delete res[key]
                }
              }
              dataList.push(res)
              if (fag === listData.length) {
                resolve(dataList)
              }
            })
          } else {
            dataList.push(item)
            resolve(dataList)
          }
        })
      }
    } else {
      resolve([])
    }
  })
}
// 获取买家用户信息
function getUserInfo(userId) {
  return new Promise(async(resolve) => {
    const ShopUser = model.shopUser.ShopUser
    const res = await ShopUser.findOne({ where: { userId }})
    resolve(res || {})
  })
}
// 获取地址信息
function getAddress(id) {
  return new Promise(async(resolve) => {
    const ShopAdderess = model.shopAddress.ShopAdderess
    const res = await ShopAdderess.findOne({ where: { id }})
    if (res) {
      res.isDefault = res.isDefault ? true : false
      resolve(res)
    } else {
      resolve({})
    }
  })
}
exports.getList = async(ctx) => {
  const { getGoodsDetail } = require('../models/utils')
  const { page, size, orderStatus } = ctx.request.query
  const userId = verify(ctx.header)
  if (!page || !size || !userId) {
    ctx.fail('参数错误')
    return
  }
  
  // 每个数据的item 异步
  function itemFn(item) {
    return new Promise(async(resolve) => {
      const goods_res = await getGoodsDetail(item.goodsId) // 获取商品信息
      const list_res = await listSelect(item.list) // 获取订单list
      const user_res = await getUserInfo(item.userId) // 获取买家用户信息
      const address_res = await getAddress(item.addressId) // 获取地址信息
      if (goods_res && list_res) {
        item['goods'] = goods_res
        item['list'] = list_res
        item['user'] = user_res
        item['address'] = address_res
        resolve(item)
      }
    })
  }
   // 总异步 方法
  function allFn() {
    return new Promise(async(resolve) => {
      const count_res = await Myorder.findAndCountAll({
        order: [
          ['createTime', 'DESC'],
        ],
        where: {
          adminId: userId,
          orderStatus: {
            [Op.like]: `%${orderStatus ? orderStatus : ''}%`
          }
        },
        offset: (page - 1) * size,
        limit: parseInt(size)
      })
      if (count_res) {
        let flag = 0
        for (let i = 0; i < count_res.rows.length; i++) {
          count_res.rows[i]['none_sku'] = count_res.rows[i].none_sku != 0
          itemFn(count_res.rows[i]).then(body_res => {
            flag++
            count_res.rows[i] = body_res
            if (flag === count_res.rows.length) {
              resolve(count_res)
            }
          })
        }
      }
    })
  }
  const res = await allFn()
  if (res) {
    ctx.success({
      total: res.count, // 总页数
      pageNum: Math.trunc((res.count + (size -1) )/size), // 分页数量
      page: parseInt(page), // 页码
      size: parseInt(size), // 页数
      list: res.rows
    })
  }
}

exports.setDFH = async(ctx) => {
  const { id, orderStatus} = ctx.request.body
  if (!id || !orderStatus || orderStatus != 'DSH') {
    ctx.fail('参数错误')
    return
  }
  
  function allFn() {
    return new Promise(async(resolve) => {
      const view_res = await Myorder.findOne({ where: { id: id }})
      if (view_res) {
        if (view_res.orderStatus == 'DFH') {
          const modify_res = await Myorder.update({ orderStatus: orderStatus }, { where: { id: id }})
          if (modify_res[0] == 1) {
            resolve('success')
          } else {
            resolve('发货失败')
          }
        } else {
          resolve('商品状态异常')
        }
      }
    })
  }

  const res = await allFn()
  if (res === 'success') {
    ctx.success('', '发货成功')
  } else {
    ctx.fail(res || '失败')
  }
}
